package view;

import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.List;

import com.toedter.calendar.JDateChooser;
import dao.SaleDAO;
import model.Sale;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.DefaultTableCellRenderer;

public class StatsFrame extends JFrame {
    private JDateChooser startDateChooser;
    private JDateChooser endDateChooser;
    private JTable salesTable;
    private DefaultTableModel tableModel;
    private JLabel totalLabel;
    private JLabel countLabel;
    private JLabel avgLabel;
    
    public StatsFrame() {
        setTitle("销售统计");
        setSize(1000, 600);
        setLayout(new BorderLayout(10, 10));
        
        // 创建日期选择器面板
        JPanel datePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        datePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        startDateChooser = new JDateChooser();
        endDateChooser = new JDateChooser();
        startDateChooser.setPreferredSize(new Dimension(150, 30));
        endDateChooser.setPreferredSize(new Dimension(150, 30));
        
        JButton queryBtn = new JButton("查询");
        styleButton(queryBtn);
        
        datePanel.add(new JLabel("开始日期："));
        datePanel.add(startDateChooser);
        datePanel.add(new JLabel("结束日期："));
        datePanel.add(endDateChooser);
        datePanel.add(queryBtn);
        
        add(datePanel, BorderLayout.NORTH);
        
        // 创建表格
        String[] columns = {"日期", "图书", "数量", "单价", "金额"};
        tableModel = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        salesTable = new JTable(tableModel);
        styleTable(salesTable);
        
        add(new JScrollPane(salesTable), BorderLayout.CENTER);
        
        // 添加统计面板
        JPanel statsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 20, 5));
        statsPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        totalLabel = new JLabel("总金额：¥0.00");
        countLabel = new JLabel("销售笔数：0");
        avgLabel = new JLabel("平均单价：¥0.00");
        
        styleLabel(totalLabel);
        styleLabel(countLabel);
        styleLabel(avgLabel);
        
        statsPanel.add(totalLabel);
        statsPanel.add(countLabel);
        statsPanel.add(avgLabel);
        
        add(statsPanel, BorderLayout.SOUTH);
        
        // 添加查询按钮事件
        queryBtn.addActionListener(e -> refreshData());
        
        setLocationRelativeTo(null);
        
        // 设置默认日期范围（当前月）
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        startDateChooser.setDate(cal.getTime());
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        endDateChooser.setDate(cal.getTime());
        
        // 初始加载数据
        refreshData();
    }
    
    private void styleTable(JTable table) {
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setRowHeight(25);
        table.getTableHeader().setReorderingAllowed(false);
        table.setOpaque(false);
        ((DefaultTableCellRenderer)table.getDefaultRenderer(Object.class)).setOpaque(false);
        
        // 设置列宽
        table.getColumnModel().getColumn(0).setPreferredWidth(150);
        table.getColumnModel().getColumn(1).setPreferredWidth(250);
        table.getColumnModel().getColumn(2).setPreferredWidth(100);
        table.getColumnModel().getColumn(3).setPreferredWidth(100);
        table.getColumnModel().getColumn(4).setPreferredWidth(100);
        
        // 设置数字列的对齐方式
        DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
        rightRenderer.setHorizontalAlignment(JLabel.RIGHT);
        rightRenderer.setOpaque(false);
        table.getColumnModel().getColumn(2).setCellRenderer(rightRenderer);
        table.getColumnModel().getColumn(3).setCellRenderer(rightRenderer);
        table.getColumnModel().getColumn(4).setCellRenderer(rightRenderer);
        
        // 设置字体
        Font font = new Font("微软雅黑", Font.PLAIN, 14);
        table.setFont(font);
        table.getTableHeader().setFont(font);
        
        // 设置表格行高亮
        table.setSelectionBackground(new Color(184, 207, 229, 150));
    }
    
    private void styleButton(JButton button) {
        button.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        button.setFocusPainted(false);
        button.setBackground(new Color(59, 89, 152));
        button.setForeground(Color.WHITE);
        button.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 15));
    }
    
    private void styleLabel(JLabel label) {
        label.setFont(new Font("微软雅黑", Font.BOLD, 14));
        label.setForeground(new Color(59, 89, 152));
    }
    
    private void refreshData() {
        Date startDate = startDateChooser.getDate();
        Date endDate = endDateChooser.getDate();
        
        if (startDate == null || endDate == null) {
            JOptionPane.showMessageDialog(this, "请选择日期范围！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        if (startDate.after(endDate)) {
            JOptionPane.showMessageDialog(this, "开始日期不能大于结束日期！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        SaleDAO dao = new SaleDAO();
        List<Sale> sales = dao.getSalesByDateRange(startDate, endDate);
        
        tableModel.setRowCount(0);
        double total = 0;
        int count = sales.size();
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Sale sale : sales) {
            Object[] row = {
                sdf.format(sale.getSaleDate()),
                sale.getBookTitle(),
                sale.getQuantity(),
                sale.getTotalPrice() / sale.getQuantity(), // 单价
                sale.getTotalPrice()
            };
            tableModel.addRow(row);
            total += sale.getTotalPrice();
        }
        
        // 更新统计信息
        totalLabel.setText(String.format("总金额：¥%.2f", total));
        countLabel.setText(String.format("销售笔数：%d", count));
        avgLabel.setText(String.format("平均单价：¥%.2f", count > 0 ? total / count : 0));
    }
}